package com.ego.admin.controller;

import com.ego.admin.po.SysAdmin;
import com.ego.admin.po.SysDepartment;
import com.ego.admin.po.SysRole;
import com.ego.admin.service.*;
import com.ego.admin.vo.AdminVo;
import com.ego.admin.vo.PasswordFormVo;
import com.ego.admin.vo.SysLoginLogVo;
import com.ego.admin.vo.SysUserSearchVo;
import com.ego.common.annotation.ControllerEndpoint;
import com.ego.common.util.Result;
import com.ego.common.vo.PageVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @program: ego
 * @description: 系统管理员
 * @author: KamTang
 * @create: 2022-11-13 10:45
 **/
@RestController
@RequestMapping("/sys/admin")
public class SysAdminController extends Administrator {

    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysAdminRoleService adminRoleService;
    @Autowired
    private SysLoginLogService loginLogService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDepartmentService departmentService;

    @PostMapping("/search")
    public Result search(@Valid @RequestBody SysUserSearchVo search) {
        PageVo<SysAdmin> page = sysAdminService.search(search);
        return Result.ok().put("page", page);
    }

    /**
     * 获取登录用户信息
     */
    @GetMapping("/info")
    public Result get() {
        SysAdmin admin = getAdmin();
        SysLoginLogVo loginLog = loginLogService.getLastLoginInfo(admin.getUsername());
        List<SysRole> roleList = roleService.getRoleInfoByUserId(admin.getUserId());
        List<Long> roleIdList = adminRoleService.queryRoleIdList(admin.getUserId());
        SysDepartment department = departmentService.getById(admin.getDepartmentId());
        admin.setRoles(roleList);
        admin.setLoginTime(loginLog.getLoginTime());
        admin.setLocation(loginLog.getLocation());
        admin.setIp(loginLog.getIp());
        admin.setRoleIdList(roleIdList);
        admin.setDepartment(department.getName());
        return Result.ok().put("admin", admin);
    }


    /**
     * 用户信息
     */
    @GetMapping("/get/{userId}")
    @RequiresPermissions("sys:user:info")
    public Result get(@PathVariable("userId") Long userId) {
        SysAdmin user = sysAdminService.getById(userId);

        // 获取用户所属的角色列表
        List<Long> roleIdList = adminRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);
        return Result.ok().put("user", user);
    }

    /**
     * 修改管理员信息
     */
    @ControllerEndpoint(exceptionMessage = "管理员信息修改失败", operation = "修改管理员信息")
    @PostMapping("/update")
    public Result update(@RequestBody AdminVo vo) {
        try {
            sysAdminService.update(SysAdmin.fromVo(vo));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 新增管理员
     */
    @ControllerEndpoint(exceptionMessage = "新增管理员失败", operation = "新增管理员")
    @PostMapping("/save")
    public Result save(@RequestBody AdminVo vo) {
        try {
            sysAdminService.saveUser(SysAdmin.fromVo(vo));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 修改密码
     */
    @ControllerEndpoint(exceptionMessage = "修改密码失败", operation = "修改密码")
    @PostMapping("/updatePwd")
    public Result updatePwd (@RequestBody PasswordFormVo passwordForm) {
        // 由于前端有数据校验，这里不需要对PasswordForm进行非空判断
        //sha256加密
        String password = new Sha256Hash(passwordForm.getPassword(), getAdmin().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(passwordForm.getNewPassword(), getAdmin().getSalt()).toHex();

        boolean flag = sysAdminService.updatePwd(getAdmin().getUserId(), password, newPassword);
        if (!flag) {
            return Result.error("原密码不正确");
        }
        return Result.ok();
    }
}
